<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Building photo controller
 */
class Bphoto extends Admin_Controller
{
    protected $permissionCreate = 'Buildings.Content.Create';
    protected $permissionDelete = 'Buildings.Content.Delete';
    protected $permissionEdit   = 'Buildings.Content.Edit';
    protected $permissionView   = 'Buildings.Content.View';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->auth->restrict($this->permissionView);
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/photos_model');
        $this->load->model('area/area_model');
        $this->load->model('vendor/vendor_model');
        $this->load->model('category/category_model');
        $this->load->model('buildings/buildingstag_model', 'buildings_tag_model');
        $this->lang->load('buildings');
        
        $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        Template::set_block('sub_nav', 'building/_sub_nav');

        Assets::add_module_js('buildings', 'buildings.js');
        Assets::add_module_js('buildings', 'photos.js');
        Assets::add_css(array('plugins/select2/select2.min.css', 'plugins/iCheck/all.css', 'plugins/datepicker/datepicker3.css'));
        Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), 
                            Template::theme_url('plugins/iCheck/icheck.min.js'), 
                            Template::theme_url('plugins/datepicker/bootstrap-datepicker.js'), 
                            Template::theme_url('js/plupload-2.1.1/plupload.full.min.js'),
                            Template::theme_url('js/plupload-2.1.1/i18n/zh_CN.js'), 
                            Template::theme_url('js/qiniu.js')
                            ));
    }

    /**
     * Display a list of Buildings data.
     *
     * @return void
     */
    public function index($targetId, $type = 1, $subType = 1, $offset = 0)
    {
        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->photos_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('buildings_delete_success'), 'success');
                } else {
                    Template::set_message(lang('buildings_delete_failure') . $this->photos_model->error, 'error');
                }
            }
        }

        $where = array('photos.deleted'=>0, 'type'=>$type, 'target_id'=>$targetId, 'sub_type'=>$subType);
        $totalRows = $this->photos_model->where($where)->count_all();
        $this->photos_model->where($where);

        $pagerUriSegment = 7;
        $pagerBaseUrl = site_url('/buildings/bphoto/index').'/'.$targetId. '/'.$type.'/'.$subType.'/';
        
        $limit  = $this->settings_lib->item('site.list_limit') ?: 15;

        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $this->pagination->initialize($this->pager);
        $this->photos_model->limit($limit, $offset);
        
        $records = !empty($records) ? $records : $this->photos_model->order_by("platform,id,category","ASC")->find_all();
        if($records){
            foreach ($records as $key => $value) {
                if($value->category){
                    $records[$key]->category = building_pic_zone()[$value->category];
                }else{
                    $records[$key]->category = "N/A";
                }
                if(empty($value->title)){
                    $records[$key]->title = "N/A";
                }
                $records[$key]->version = !empty($records[$key]->version) ? $records[$key]->version :"无";
                
            }
        }
        Template::set('records', $records);

        Template::set('index_url', $pagerBaseUrl);
        Template::set('toolbar_title', lang('buildings_manage'));

        // Template::render();
        $data['index_url'] = $pagerBaseUrl;
        $data['records'] = $records;
        $data['photoType'] = $type;
        $data['photoSubType'] = $subType;
        $data['targetId'] = $targetId;
        $this->load->view('bphoto/header');
        $this->load->view('bphoto/index', $data);
        $this->load->view('bphoto/footer');
    }
    
    /**
     * Create a Buildings object.
     *
     * @return void
     */
    public function create($targetId, $type = 1, $subType = 1)
    {
        $this->auth->restrict($this->permissionCreate);
        
        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_buildings('insert', 0, $subType)) {
                log_activity($this->auth->user_id(), lang('buildings_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_create_success'), 'success');

                $pagerBaseUrl = site_url('/buildings/bphoto/index').'/'.$targetId. '/'.$type.'/'.$subType.'/';
                redirect($pagerBaseUrl);
            }

            // Not validation error
            if ( ! empty($this->photos_model->error)) {
                Template::set_message(lang('buildings_create_failure') . $this->photos_model->error, 'error');
            }
        }

        // Template::render();
        $data['photoType'] = $type;
        $data['photoSubType'] = $subType;
        $data['targetId'] = $targetId;
        foreach (building_pic_zone() as $key => $value) {
            $tmp = $this->photos_model->where("target_id= {$targetId} and category = {$key} and sub_type = 3 and deleted = 0")->group_by('version')->find_all();
            if($tmp){
                $zone_count[] = $value."(".count($tmp).")";
            }else{
                $zone_count[] = $value."(0)";
            }
        }
        $data['buildingPicZone'] = $zone_count;
        //dump($data['buildingPicZone']);exit();
        $this->load->view('bphoto/header');
        $this->load->view('bphoto/create', $data);
        $this->load->view('bphoto/footer');
    }
    /**
     * Allows editing of Buildings data.
     *
     * @return void
     */
    public function edit($targetId, $type = 1, $subType = 1)
    {
        $id = $this->uri->segment(7);
        if (empty($id)) {
            Template::set_message(lang('buildings_invalid_id'), 'error');

            redirect(SITE_AREA . '/building/buildings');
        }
        
        if (isset($_POST['save'])) {
            $this->auth->restrict($this->permissionEdit);

            if ($this->save_buildings('update', $id, $subType)) {
                log_activity($this->auth->user_id(), lang('buildings_act_edit_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_edit_success'), 'success');
                $pagerBaseUrl = site_url('/buildings/bphoto/index').'/'.$targetId. '/'.$type.'/'.$subType.'/';
                redirect($pagerBaseUrl);
            }

            // Not validation error
            if ( ! empty($this->photos_model->error)) {
                Template::set_message(lang('buildings_edit_failure') . $this->photos_model->error, 'error');
            }
        }
        
        elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->photos_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('buildings_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_delete_success'), 'success');

                redirect(SITE_AREA . '/building/buildings');
            }

            Template::set_message(lang('buildings_delete_failure') . $this->photos_model->error, 'error');
        }
        
        $photo = $this->photos_model->find($id);
        $normal_tags = explode(',', $photo->desc);
        //$photo->category = building_pic_zone()[$photo->category];
        $data['normal_tags'] = $normal_tags;
        //dump($photo);exit();
        $data['photoType'] = $photo->type;
        $data['photoSubType'] = $photo->sub_type;
        $data['targetId'] = $photo->target_id;
        $data['photo'] = $photo;
        foreach (building_pic_zone() as $key => $value) {
            $tmp = $this->photos_model->where("target_id= {$targetId} and category = {$key} and sub_type = 3 and deleted = 0")->group_by('version')->find_all();
            if($tmp){
                $zone_count[] = $value."(".count($tmp).")";
            }else{
                $zone_count[] = $value."(0)";
            }
        }
        $data['buildingPicZone'] = $zone_count;
        $this->load->view('bphoto/header');
        $this->load->view('bphoto/edit', $data);
        $this->load->view('bphoto/footer');
    }

    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------

    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    private function save_buildings($type = 'insert', $id = 0, $subType)
    {
        if ($type == 'update') {
            $_POST['id'] = $id;
        }

        // Validate the data
        // $this->form_validation->set_rules($this->buildings_model->get_validation_rules());
        // if ($this->form_validation->run() === false) {
        //     return false;
        // }

        // Make sure we only pass in the fields we want
        $post = $this->input->post();
        $data = $this->photos_model->prep_data($post);



        // Additional handling for default values should be added below,
        // or in the model's prep_data() method

        // 初始化缩略图持久化
        require APPPATH.'third_party/Qiniu-7.0.7/autoload.php';
        // 公司账号
        $accessKey = config_item('qiniu.access_key');
        $secretKey = config_item('qiniu.secret_key');
        // 构建鉴权对象
        $auth = new Qiniu\Auth($accessKey, $secretKey);
        $bucket = config_item('qiniu.bucket');
        // $notifyUrl = 'http://375dec79.ngrok.com/notify.php';
        // $pipeline = 'pipeline_building_imageView2';
        $pfop = new Qiniu\Processing\PersistentFop($auth, $bucket);

        $return = false;
        $domain = building_domain()[$post['domain']];
        if ($type == 'insert') {
            foreach ($data as $key => $value) {
                if($value['desc']){
                    $data[$key]['desc'] = implode(",", $value['desc']);
                }else{
                    $data[$key]['desc'] = "";
                } 
                $data[$key]['category'] = !empty($post['pic_zone'][$key]) ? $post['pic_zone'][$key] : "0";
                $data[$key]['version'] = !empty($post['version'][$key]) ? $post['version'][$key] : "0";
                $data[$key]['domain'] = $domain;
            }
            $id = $this->photos_model->addPhotos($data);

            if (is_numeric($id)) {
                // 缩略图持久化
                foreach ($data as $key => $val) {
                    $key = $val['url'];
                    $platform = $val['platform'];
                    $fops = $this->fops($key, $platform, $subType);
                    if ($fops) {
                        $exeReturn = $pfop->execute($key, $fops);
                    }
                }
                $return = $id;
            }
        } elseif ($type == 'update') {
            if($data['desc']){
                $data['desc'] = implode(",", $data['desc']);
            }else{
                $data['desc'] = "";
            }
            $data['category'] = !empty($post['pic_zone'][0]) ? $post['pic_zone'][0] : "0";
            $data['version'] = !empty($post['version'][0]) ? $post['version'][0] : "0";
            $data['domain'] = $domain;

            $return = $this->photos_model->update($id, $data);

            // 缩略图持久化
            $key = $data['url'];
            $platform = $data['platform'];
            $fops = $this->fops($key, $platform, $subType);
            if ($fops) {
                $exeReturn = $pfop->execute($key, $fops);
            }
        }

        return $return;
    }

    /**
     * 管道命令
     * @param  string $key      七牛文件key
     * @param  int $platform PC端、移动端
     * @return array           
     */
    private function fops($key, $platform, $subType) {
        $bucket = config_item('qiniu.bucket');
        // 命令
        // $imageView20 = 'imageView2/0'; // 移动端切图模式
        $imageView22 = 'imageView2/2'; // PC端切图模式
        // PC端
        // 特色图片
        $fops[3] = ["{$imageView22}/w/1400/interlace/1|saveas/".base64_encode("$bucket:".$key."-large.1400")]; 
        // 顶部大图
        $fops[5] = ["{$imageView22}/w/1920/interlace/1|saveas/".base64_encode("$bucket:".$key."-large.1920"), 
                    "{$imageView22}/w/2800/interlace/1|saveas/".base64_encode("$bucket:".$key."-medium.2x.2800"), 
                    "{$imageView22}/w/1400/interlace/1|saveas/".base64_encode("$bucket:".$key."-medium.1400"), ]; 
        if ($platform == 2) {
            // 移动端
            // 特色图片
            $fops[3] = ["{$imageView22}/w/540/interlace/1|saveas/".base64_encode("$bucket:".$key."-small.540")];
            // 顶部大图
            $fops[5] = $fops[3];
        }
        return isset($fops[$subType]) ? $fops[$subType] : false;
    }

    /**
     * 删除数据
     */
    public function delete($targetId, $type = 1, $subType = 1)
    {
        $id = $this->uri->segment(7);
        if (empty($id)) {
            Template::set_message(lang('channel_invalid_id'), 'error');

            redirect(SITE_AREA . '/building/buildings');
        }

        $this->auth->restrict($this->permissionDelete);

        if ($this->photos_model->delete($id)) {
            log_activity($this->auth->user_id(), lang('channel_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'channel');
            Template::set_message(lang('channel_delete_success'), 'success');

            $pagerBaseUrl = site_url('/buildings/bphoto/index').'/'.$targetId. '/'.$type.'/'.$subType.'/';
            redirect($pagerBaseUrl);
        }

    }

    /**
     * 七牛上传token
     * @return json
     */
    public function qiniuUploadToken() {
        require APPPATH.'third_party/Qiniu-7.0.7/autoload.php';

        // parent::showProfiler(false);
        $this->output->enable_profiler(false);

        // 个人测试账号
        // $accessKey = 'sSRSrUD-G4Jvj6DUkoH_KwjSZwj39wCYL7nK7ZPx';
        // $secretKey = 'eStkT02p6sR5m2SYZSPBfn2cGmqvyB97ohw28AgI';
        // 公司账号
        $accessKey = config_item('qiniu.access_key');
        $secretKey = config_item('qiniu.secret_key');

        // 构建鉴权对象
        $auth = new Qiniu\Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = config_item('qiniu.bucket');

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        echo json_encode(array('uptoken'=>$token));
    }
}